package indi.mozping.concurrentutil.countdownlatchp;

import indi.mozping.tools.SleepTools;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author by mozping
 * @Classname CountDownLatchTest
 * @Description CountDownLatch测试类
 * 初始化了CountDownLatch类，初始化若干个扣除点，比如5个，
 * 在主线程中初始化5个业务线程，每个业务线程执行完成后，减去一个扣除点，主线程会等待扣除点为0后才执行，
 * 这里每次默认扣除一个扣除点，注意如果初始化了6个扣除点，五个线程只扣除5次，那么主线程就会一直阻塞住
 * @Date 2019/1/2 15:51
 */
public class CountDownLatchTest {

    private static CountDownLatch countDownLatch = new CountDownLatch(5);

    /**
     * 主线程
     */
    public static void main(String[] args) throws InterruptedException {

        for (int i = 1; i <= 5; i++) {
            new MyBussinessThread().start();
        }

        //主线程等待
        countDownLatch.await(15, TimeUnit.SECONDS);
        System.out.println("主线程等待结束后执行...，剩余扣除点：" + countDownLatch.getCount());


    }

    /**
     * 业务线程
     */
    private static class MyBussinessThread extends Thread {
        @Override
        public void run() {
            System.out.println("业务线程 [" + Thread.currentThread().getName() + "] 处理业务...");
            //随机休眠10以内的时间
            SleepTools.randomSecond(10);
            System.out.println("业务线程 [" + Thread.currentThread().getName() + "] 处理业务完毕...");
            //完成后扣减一次
            countDownLatch.countDown();
        }
    }
}
